import time

from pb.comfuc import Comfuc
from pb.getPBodds import GetPBodds
from fb.getFBodds import GetFBodds
from utils.mail import Email
from pb.queueProcessor import QueueProcessor
from crud import match as crud_match
from utils.database import SessionLocal
import logging

class Service:

    queueProcessor = QueueProcessor()
    weight_data = {}
    getPBodds = GetPBodds()
    getFBodds = GetFBodds()
    def run(self):
         # key是bpsport，value是[上下盘权重,大小球权重，计算次数]

        pbSports = self.getPBodds.getList()

        fbSports = self.getFBodds.getList()
        if pbSports is None or fbSports is None:
            time.sleep(2)
            logging.info('死机了吗')
            return
        for pbSport in pbSports:
            for fbSport in fbSports:

                if Comfuc.similarity(pbSport.match,fbSport.match) and fbSport.start_time==pbSport.start_time:
                    #print(pbSport.match+'----------------'+fbSport.match)
                    pb_ou_key ,pb_ou_value = Comfuc.find_min_diff_array(pbSport.full_ou_odd)
                    fb_ou_value = fbSport.full_ou_odd.get(pb_ou_key)
                    #print(f'比赛{pbSport.match} 平博大{pb_ou_key}赔率{pb_ou_value[0]} FB赔率{fb_ou_value[0]}')
                    #print(f'比赛{pbSport.match} 平博小{pb_ou_key}赔率{pb_ou_value[1]} FB赔率{fb_ou_value[1]}')
                    ou_weight = pb_ou_value[0] - fb_ou_value[0] -(pb_ou_value[1] - fb_ou_value[1])
                    #print(f'weight={ou_weight}')#负数买大，正数买小，0.001以下数误差不计算 ，负数买主队，正数买客队
                    pb_hdp_key, pb_hdp_value = Comfuc.find_min_diff_array(pbSport.full_hdp_odd)
                    fb_hdp_value = fbSport.full_hdp_odd.get(pb_hdp_key)
                    hdp_weight = pb_hdp_value[0] - fb_hdp_value[0] - (pb_hdp_value[1] - fb_hdp_value[1])

                    weight_value = self.weight_data.get(pbSport)
                    if weight_value is None :
                        self.weight_data[pbSport] = [hdp_weight,ou_weight,1,0]#索引3位置是标记消息只发送一次，如果是1，表示不做计算
                    else:
                        v = self.weight_data[pbSport]
                        if v[3]==0:
                            if pbSport.start_time/1000 - time.time()  > 3*60:
                                self.weight_data[pbSport] = [v[0]+hdp_weight,v[1]+ou_weight,v[2]+1,0]
                            else:
                                self.weight_data[pbSport] = [v[0]+hdp_weight,v[1]+ou_weight,v[2]+1,1]
                        elif v[3]==1:
                            self.notify(fbSport,[pb_hdp_key,pb_ou_key],v)
                            #通知完成之后标记为2
                            self.weight_data[pbSport] = [v[0] + hdp_weight, v[1] + ou_weight, v[2] + 1, 2]


    def test(self,aa):
        print(aa)

    def notify(self,fbSport,pk,weight):
        count = weight[2]
        hdp_weight = weight[0]/count
        ou_weight = weight[1]/count
        logging.info('----------------------')
        if(count>100):
            from schemas.match import MatchCreate
            match_data = MatchCreate(
                league=fbSport.league,
                home=fbSport.home,
                away=fbSport.away,
                start_time=fbSport.start_time,
                random=Comfuc.generate_random_letters(),
                prediction = "Over 10.5",
                hash="1234567890",
                fb_id =00000000,
                weight = 0.00000
            )
            logging.info(f'------联赛：{fbSport} | 赔率{weight}-----')
            if ou_weight > 0.050:
                logging.info(f'联赛：{fbSport.league} | 比赛{fbSport.match}')
                logging.info(f'权重{ou_weight},赔率{fbSport.full_ou_odd}')
                logging.info(f'买小{pk[1]}')
                match_data.fb_id = fbSport.sport_id
                match_data.weight=ou_weight
                match_data.prediction= f'Under {pk[1]}'
                match_data.hash = Comfuc.generate_hash(fbSport.home,fbSport.away,match_data.prediction,match_data.random)
                self.save_db(match_data)
                self.queueProcessor.put_item(f'{fbSport.league}:  {fbSport.match} --- Under {pk[1]} \n')
                #self.sendMail(fbSport.league, f' {fbSport.match}\n Under {pk[1]}')
            if ou_weight < -0.050:
                logging.info(f'联赛：{fbSport.league} | 比赛{fbSport.match}')
                logging.info(f'权重{ou_weight},赔率{fbSport.full_ou_odd}')
                logging.info(f'买大{pk[1]}')
                match_data.fb_id = fbSport.sport_id
                match_data.weight = ou_weight
                match_data.prediction = f'Over {pk[1]}'
                match_data.hash = Comfuc.generate_hash(fbSport.home, fbSport.away, match_data.prediction,
                                                       match_data.random)
                self.save_db(match_data)
                self.queueProcessor.put_item(f'{fbSport.league}:  {fbSport.match} --- Over {pk[1]} \n')
                #self.sendMail(fbSport.league, f' {fbSport.match}\n Over {pk[1]}')
            if hdp_weight > 0.050:
                logging.info(f'联赛：{fbSport.league} | 比赛{fbSport.match}')
                logging.info(f'权重{hdp_weight},赔率{fbSport.full_hdp_odd}')
                logging.info(f'客队{Comfuc.invert_sign(pk[0])}')
                match_data.fb_id = fbSport.sport_id
                match_data.weight = hdp_weight
                match_data.prediction = f'Away {Comfuc.invert_sign(pk[0])}'
                match_data.hash = Comfuc.generate_hash(fbSport.home, fbSport.away, match_data.prediction,
                                                       match_data.random)
                self.save_db(match_data)
                self.queueProcessor.put_item(f'{fbSport.league}:  {fbSport.match} --- Away {Comfuc.invert_sign(pk[0])} \n')
                #self.sendMail(fbSport.league, f' {fbSport.match}\n Away {Comfuc.invert_sign(pk[0])}')
            if hdp_weight < -0.050:
                logging.info(f'联赛：{fbSport.league} | 比赛{fbSport.match}')
                logging.info(f'权重{hdp_weight},赔率{fbSport.full_hdp_odd}')
                logging.info(f'主队{Comfuc.sign(pk[0])}')
                match_data.fb_id = fbSport.sport_id
                match_data.weight = hdp_weight
                match_data.prediction = f'Home {Comfuc.sign(pk[0])}'
                match_data.hash = Comfuc.generate_hash(fbSport.home, fbSport.away, match_data.prediction,
                                                       match_data.random)
                self.save_db(match_data)
                self.queueProcessor.put_item(f'{fbSport.league}:  {fbSport.match} --- Home {Comfuc.sign(pk[0])} \n')
                #self.sendMail(fbSport.league,f' {fbSport.match}\n Home {Comfuc.sign(pk[0])}')


    def sendMail(self,subject,info):
        email = Email()
        email.set_subject(subject)
        email.set_message(info)
        email.send()


    def save_db(self,match_data):
        db = SessionLocal()
        db_match = crud_match.create(db, obj_in=match_data.model_dump())

if __name__ == "__main__":
    service =Service()
    while True:
        try:
            service.run()
            time.sleep(8)
        except Exception as e:
            #print("Response Text:", response.text)
            logging.info(f"请求过程中发生错误：{e}")